package cn.zhangxin.pethome.system.login.controller;

import cn.zhangxin.pethome.config.Wxconfig;
import cn.zhangxin.pethome.constants.BaseConstants;
import cn.zhangxin.pethome.system.login.domain.Bind;
import cn.zhangxin.pethome.system.login.domain.RequsetCode;
import cn.zhangxin.pethome.system.login.domain.ResponseToken;
import cn.zhangxin.pethome.system.logininfo.domain.LoginRo;
import cn.zhangxin.pethome.system.logininfo.domain.Logininfo;
import cn.zhangxin.pethome.system.logininfo.service.impl.LogininfoServiceImpl;
import cn.zhangxin.pethome.system.user.domain.User;
import cn.zhangxin.pethome.system.user.service.IUserService;
import cn.zhangxin.pethome.system.wxuser.domain.Wxuser;
import cn.zhangxin.pethome.system.wxuser.service.IWxuserService;
import cn.zhangxin.pethome.utils.*;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/login")
@Api(value = "用户登录",description="用户登录相关功能")
public class LoginController {
    @Autowired
    private Wxconfig wxconfig;
    @Autowired
    private IUserService userService;
    @Autowired
    private IWxuserService wxuserService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoServiceImpl logininfoService;

    @RequestMapping("/wechat")
    @ApiOperation(value = "微信登录" )
    public AjaxResult LoginToWechat(@RequestBody RequsetCode requsetCode){
        //获得令牌
        if (requsetCode.getCode()==null){
            throw new BusinessException("非法访问");
        }
        //1.获得url
        String accessTokenUrl = wxconfig.getAccessTokenUrl(requsetCode.getCode());
        //2.调用工具类发送请求，获得token 拿到令牌
        String result = HttpClientUtils.httpGet(accessTokenUrl);
        //3.将json字符串转化为对象
        ResponseToken responseToken = JSONObject.parseObject(result, ResponseToken.class);
        if (responseToken.getAccess_token()==null || "".equals(responseToken.getAccess_token().trim())){
            throw new BusinessException("非法访问");
        }
        //4.通过返回的token令牌查询用户数据
        //拼接userInfoUrl
        String userinfoUrl = wxconfig.getUserinfoUrl(responseToken.getAccess_token(), responseToken.getOpenid());
        //发送请求,获得用户数据
        String userInfo = HttpClientUtils.httpGet(userinfoUrl);
        //5.将用户信息转为对象
        Wxuser wxuser = JSONObject.parseObject(userInfo, Wxuser.class);
        //6.拿到用户数据,判断
        //6.1 用户第一次访问 添加数据 6.2 用户微信登录 但没绑定账号 跳转绑定页面 6.3 用户微信登录 绑定账号直接登录
        //从数据库中查询出来的wxuser
        Wxuser wxusers = wxuserService.findOneByUnionidWxuser(responseToken.getUnionid());
        //6.1
        if (wxusers==null){
            //6.1.1用户第一次微信登录直接保存信息，跳转绑定页面
            wxuserService.add(wxuser);
            return AjaxResult.error().setMsg("NOBIND").setData(wxuser.getUnionid());
        }else {
            //6.2
            if (wxusers.getUserId()==null){
                //非第一次微信登录，未绑定
                return AjaxResult.error().setMsg("NOBIND").setData(wxuser.getUnionid());
            }else { //6.3用户微信登录 绑定账号直接登录
                //查询用户信息
                User user = userService.findOne(wxusers.getUserId());
                //将token保存到user中
                user.setToken(responseToken.getAccess_token());
                Logininfo one = logininfoService.findOne(user.getLogininfoId());
                LoginRo loginRo = new LoginRo();
                BeanUtils.copyProperties(one,loginRo);
                loginRo.setAutoLogin(false);//自动登录
                return logininfoService.account(loginRo);
            }
        }

    }

    @PostMapping("/binder/wechat")
    @ApiOperation(value = "绑定授权" )
    public AjaxResult LoginToWechatBinder(@RequestBody Bind bind){

            if (bind.getPhone()==null || !MobileUtil.checkPhone(bind.getPhone())){
                return AjaxResult.error().setMsg("请输入正确的手机号");
            }
            if (bind.getUnionid()==null){
                return AjaxResult.error().setMsg("非法访问");
            }
            Object code = redisTemplate.opsForValue().get(bind.getPhone() + BaseConstants.Redis.BIND);
            if (code==null){
                return AjaxResult.error().setMsg("短信验证码已过期");
            }
            String codes = code.toString();
            if (!codes.equals(bind.getVerifyCode().trim())){
                return AjaxResult.error().setMsg("验证码错误");
            }
            //校验手机号是否已经被绑定
            User byPhone = userService.findPhone(bind.getPhone());

            if (byPhone!=null){
                Wxuser byUserId = wxuserService.findOneByUserIdWxuser(byPhone.getId());
                if(byUserId != null){//证明已经绑定了
                    return AjaxResult.error().setMsg("该手机号已经被绑定了");
                }else {//没有绑定
                    executeBind(bind, byPhone);
                }
            }else{
                //补全t_user表
                User user = new User();
                user.setPhone(bind.getPhone());
                user.setPassword("666666");
                //发送短信 告知用户默认密码

                Long userid = userService.addBind(user);
                user.setId(userid);
                executeBind(bind,user);
            }
            //登录跳转
            byPhone = userService.findPhone(bind.getPhone());
            LoginRo loginRO = new LoginRo();
            loginRO.setPassword(byPhone.getPassword());
            loginRO.setUsername(byPhone.getUsername());
            loginRO.setType(BaseConstants.LogininfoType.STATE_USER);
            loginRO.setAutoLogin(false);
            return logininfoService.account(loginRO);

    }
    private void executeBind(Bind bind, User byPhone) {
        Wxuser byUnionid = wxuserService.findOneByUnionidWxuser(bind.getUnionid());
        if (byUnionid == null) {
            throw new BusinessException("非法访问!");
        }
        byUnionid.setUserId(byPhone.getId());
        wxuserService.update(byUnionid);
    }

}
